package com.biglead.mini.service.impl;

import com.alibaba.fastjson.JSON;
import com.biglead.common.config.Constant;
import com.biglead.common.pojo.OrderInfo;
import com.biglead.common.pojo.OrderMessage;
import com.biglead.mini.config.SnowFlakeCompone;
import com.biglead.mini.service.OrderService;
import com.biglead.mini.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private SnowFlakeCompone snowFlakeCompone;
    @Autowired
    private RedisService redisService;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;
    @Value("${spring.kafka.template.default-topic}")
    private String kafkaTopic;

    @Override
    public String asyncCreatOrder(Long userId, Long goodsId) {
        //判断库存
        Boolean aBoolean = redisService.hasKey(Constant.GOOOD_STOCK + goodsId);
        if (!aBoolean) {
            throw new RuntimeException("库存不足");
        }
        //雪花算法订单号
        String nextId = snowFlakeCompone.getInstance().nextId() + "";
        //Redis保存预订单号状态 1 为正在处理中 2为下单完成 3为下单失败
        redisService.set(Constant.ORDER_SN + nextId, 1);
        //设置过期时间1分钟
        redisService.expire(Constant.ORDER_SN + nextId, 60);

        OrderMessage message = new OrderMessage();
        message.setSn(nextId);
        message.setUserId(userId);
        message.setGoodsId(goodsId);
        message.setNum(1);//下单商品数量
        //kafka下单消息发送
        kafkaTemplate.send(kafkaTopic, JSON.toJSONString(message));//使用send方法发送消息，需要传入topic名称
        log.info("消息发送至 Kafka 成功");

        return nextId;
    }

    @Override
    public OrderInfo getOrderInfoBySn(String sn) {
        Boolean aBoolean = redisService.hasKey(Constant.ORDER_SN + sn);
        if (!aBoolean) {
            throw new RuntimeException("下单失败 库存不足");
        }
        //1正在处理中
        int statues = Integer.parseInt(redisService.get(Constant.ORDER_SN + sn).toString());
        if (statues == 1) {
            return null;
        }
        if (statues == 3) {
            throw new RuntimeException("下单失败 库存不足");
        }
        //缓存订单信息
        OrderInfo orderInfo = (OrderInfo) redisService.get(Constant.ORDER_SN_NORMAL + sn);
        return orderInfo;
    }
}
